<template>
  <SubLayout :breadcrumb="false" @refresh="() => { }" :showRefresh="false">
    <template #bread>
      <router-link to="/system/auth/list">认证管理</router-link>
      <el-icon class="route-icon"> <arrow-right /> </el-icon>
    </template>
    <template #default>
      <section class="form-container">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :labelWidth="100">
          <h4 class="divider">请求基础</h4>
          <ul class="flex">
            <li>
              <el-form-item label="认证名称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入认证名称" />
              </el-form-item>
            </li>
            <li>
              <el-form-item label="缓存时间" prop="cacheTime">
                <el-input-number v-model="ruleForm.cacheTime" :min="0" :max="9999999999999999" />
                <span>（单位：秒）</span>
              </el-form-item>
            </li>
          </ul>
          <h4 class="divider">接口配置</h4>
          <ul class="flex" v-if="ruleForm.authType == 0">
            <li>
              <el-form-item label="接口类型" prop="authType">
                <el-select v-model="ruleForm.authType" placeholder="请选择接口类型" @change="changeType">
                  <el-option label="RESTFUL_API" :value="0" />
                  <el-option label="JAVA定制" :value="1" />
                </el-select>
              </el-form-item>
            </li>
            <li>
              <el-form-item label="接口URL" prop="url">
                <el-input v-model="ruleForm.url" placeholder="请输入相对路径" />
              </el-form-item>
            </li>
            <li>
              <el-form-item label="支持格式" prop="inParamsFormat">
                <el-radio-group v-model="ruleForm.inParamsFormat" @change="chaneParamsFormat">
                  <el-radio label="FORMDATA">FORMDATA</el-radio>
                  <el-radio label="JSON">JSON</el-radio>
                </el-radio-group>
              </el-form-item>
            </li>
            <li>
              <el-form-item label="请求方式" prop="httpMethod">
                <el-select v-model="ruleForm.httpMethod" placeholder="请选择">
                  <el-option value="GET">GET</el-option>
                  <el-option value="POST">POST</el-option>
                  <el-option value="DELETE">DELETE</el-option>
                  <el-option value="PATCH">PATCH</el-option>
                </el-select>
              </el-form-item>
            </li>
            <li>
              <el-form-item label="接口文档" prop="docUrl">
                <UploadFile v-model="ruleForm.docUrl" />
              </el-form-item>
            </li>
            <li style="width: 100%;">
              <el-form-item label="备注" prop="memo">
                <el-input type="textarea" v-model="ruleForm.memo" placeholder="请输入备注" />
              </el-form-item>
            </li>
            <li style="width: 100%;">
              <RequestQuery v-model="ruleForm" />
            </li>
          </ul>
          <ul class="flex" v-else>
            <li>
              <el-form-item label="接口类型" prop="authType">
                <el-select v-model="ruleForm.authType" placeholder="请选择接口类型" @change="changeType">
                  <el-option label="RESTFUL_API" :value="0" />
                  <el-option label="JAVA定制" :value="1" />
                </el-select>
              </el-form-item>
            </li>
            <li>
              <el-form-item label="类名称" prop="classFullName">
                <el-input v-model="ruleForm.classFullName" placeholder="请输入类名称" />
              </el-form-item>
            </li>
            <li>
              <el-form-item label="jar文件包" prop="url">
                <UploadFile v-model="ruleForm.url" fileTypeName="jar文件包" action="/auth/plugin/upload" tips="上传自定义的jar包文件"/>
              </el-form-item>
            </li>
            <li>
              <el-form-item label="接口文档" prop="docUrl">
                <UploadFile v-model="ruleForm.docUrl" />
              </el-form-item>
            </li>
            <li style="width: 100%;">
              <el-form-item label="备注" prop="memo">
                <el-input type="textarea" v-model="ruleForm.memo" placeholder="请输入备注" />
              </el-form-item>
            </li>
          </ul>
        </el-form>
        <div class="request-table">
          <h5>出参格式转换</h5>
          <ResponseTable
            :tableData="ruleForm.outputFormatList"
            @callRequest="
              (value) => {
                ruleForm.outputFormatList = value;
              }
            "
          />
        </div>
        <div class="test-result">
          <h4 class="divider">
            测试结果
            <el-button type="primary" class="fr" @click="testApi" :loading="contactLoading">测试接口</el-button>
          </h4>
          <div class="code-box json-format">
            <pre v-html="syntaxHighlight(testData)"></pre>
          </div>
        </div>
      </section>
    </template>
    <template #footer>
      <footer>
        <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" icon-color="red"
          title="你确定要取消本次的编辑吗?" @confirm="router.go(-1)">
          <template #reference>
            <el-button>取消</el-button>
          </template>
        </el-popconfirm>
        <el-button type="primary" :loading="loading" @click="onSubmit">保存</el-button>
      </footer>
    </template>
  </SubLayout>

</template>

<script>

import { reactive, ref, onMounted, defineComponent, computed,watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { createAuth, updateAuth, getAuthDetail, ifcallVersion } from "@/api/adaptation";
import { InfoFilled, ArrowRight } from "@element-plus/icons-vue";
import useEditDrawer from "@/hooks/useEditDrawer";
import {
  syntaxHighlight,
  html2Escape,
  queryLastName,
  obj2String,
  string2obj,
  arr2StringJoinIndex
} from "@/utils/index.js";
// 组件调用
import SubLayout from '@/components/SubLayout';
import RequestQuery from "./components/RequestQuery.vue";
import UploadFile from "./components/UploadFile.vue";
import ResponseTable from "./components/ResponseTable.vue";


export default defineComponent({
  components: { RequestQuery,UploadFile, SubLayout, ArrowRight, useEditDrawer,ResponseTable },
  emits: ["callEdit"],

  setup(props, { emit }) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute()
    // 表单相关内容
    const DEFAULT_FORM = {
      authType: 0,
      cacheTime: 1000,
      classFullName: "",
      httpMethod: "GET",
      id: route.params.id ? route.params.id : null,
      memo: "",
      name: "",
      outputFormatList: [],
      outputFormatJson:'',
      url: "",
      docUrl: "",
      inParamsFormat: "FORMDATA",
      inParamsJson: null,
      inParams: { header: [], queryParam: [], body: [] },
    }
    const editType = ref(DEFAULT_FORM.id ? 'update' : 'create')
    const {
      ruleForm,
      ruleFormRef,
      loading,
    } = useEditDrawer({
      createApi: createAuth,
      editApi: updateAuth,
      defaultForm: DEFAULT_FORM,
      emit,
      type: editType.value,
      props: {
        ...props,
        type: editType.value,
      },
    });
    const rules = computed(() => {
      const baseRules = {
        name: [{ required: true, transform: (value) => (value ? value.trim() : ''), message: "请填写认证名称" }],
        cacheTime: [{ required: true, message: "请选择缓存时间" }],
        authType: [{ required: true, message: "请选择接口类型" }],
        inParamsFormat: [{ required: true, message: "请选择支持格式" }],
        httpMethod: [{ required: true, message: "请选择请求格式" }],
        url: [{ required: true, transform: (value) => (value ? value.trim() : ''), message: "请填写接口URL" }],
      };
      const jarRules = {
        name: [{ required: true, transform: (value) => (value ? value.trim() : ''), message: "请填写认证名称" }],
        classFullName: [{ required: true, transform: (value) => (value ? value.trim() : ''), message: "请填写类名称" }],
        cacheTime: [{ required: true, message: "请选择缓存时间" }],
        authType: [{ required: true, message: "请选择接口类型" }],
        url: [{ required: true, message: "请上传jar文件包" }],
      };
      return ruleForm.value.authType == 0 ? baseRules : jarRules;
    });


    const contactLoading = ref(false);
    const requsetStu = reactive([]);
    const testData = ref({});
    const addRequestRow = () => {
      requsetStu.push({ paramName: "" });
    };


    const chaneParamsFormat = (val) => {
      if (val == "ruleForm") {
        ruleForm.value.inParamsJson.body = []
      } else {
        ruleForm.value.inParamsJson.body = ""
      }
    }
    const testApi = async () => {
      contactLoading.value = true;
      testData.value = "";
      let data = {...ruleForm.value};
      data.inParamsJson = obj2String(ruleForm.value.inParams)
      try {
        let res = await ifcallVersion(data);
        console.log(res.data)
        testData.value = html2Escape(res);
        
        contactLoading.value = false;
      } catch (e) {
        contactLoading.value = false;
      }
    };

    const createFn = async (data) => {
      const res = await createAuth(data);
      loading.value = false;
      if (res.status === 200 || res.status === 201) {
        ElMessage.success("新增成功");
        router.go(-1)
      }
    }
    const editFn = async (data) => {
      const res = await updateAuth(data);
      loading.value = false;
      if (res.status === 200 || res.status === 201) {
        ElMessage.success("修改成功");
        router.go(-1)
      }
    }
    // 提交
    const submit = () => {
      loading.value = true;
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          const para = {...ruleForm.value}
          delete para.inParams
          editType.value === "create"
            ? createFn(para).catch(() => {
              loading.value = false;
            })
            : editFn(para).catch(() => {
              loading.value = false;
            });
        } else {
          ElMessage.warning("请仔细检查是否有必填字段没有填写！");
          loading.value = false;
          return false;
        }
      });
    };
    const onSubmit = () => {
      ruleForm.value.inParamsJson = obj2String(ruleForm.value.inParams)
      console.log(ruleForm.value)
      submit()

    }
    const getDetail = async () => {
      const res = await getAuthDetail(ruleForm.value.id)
      res.data.inParams = string2obj(res.data.inParamsJson)
      res.data.outputFormatList = res.data.outputFormatJson?string2obj(res.data.outputFormatJson): []
      ruleForm.value = { ...ruleForm.value, ...res.data }
    }
    const changeType = () => {
      ruleForm.value.url = ''
    }
    onMounted(() => {
      if (ruleForm.value.id) {
        getDetail()
      }
    });
    return {
      ruleForm,
      ruleFormRef,
      rules,
      loading,
      submit,

      changeType,
      requsetStu,

      addRequestRow,
      testApi,
      contactLoading,
      syntaxHighlight,
      testData,






      queryLastName,
      router,
      InfoFilled,
      chaneParamsFormat,
      onSubmit
    };
  },
});
</script>
<style lang="scss" scoped>
.outpramas-header {
  font-size: 14px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  >li {
    width: 48%;
  }
}

.el-select {
  width: 100%;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

.page-main {
  position: relative;
}

footer {
  text-align: right;
  margin-top: 20px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70px;
  line-height: 70px;
  padding: 0 20px;
  background: #fff;
}

.form-container {
  padding-bottom: 100px !important;
}
</style>
